﻿Imports Models.Solution
Imports System.ComponentModel.DataAnnotations
Imports System.Data.Spatial

Public Class Projects
    Inherits BaseService

    Sub New(request As System.Net.Http.HttpRequestMessage)
        Me.loadToken(request)
    End Sub
    Sub New(token As String)
        Me.token = token
    End Sub

    ''' <summary>
    ''' Gets the specified id.
    ''' </summary>
    ''' <param name="id">The id.</param>
    ''' <returns></returns>
    Public Function [Get](id As Integer) As ProjectVO
        Try
            Me.checkAccess("GETPROJECT")
            Dim oEntity As ProjectVO

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")
                Dim oDataEntity As Data.BaseModel.Project = (From u In oDB.Projects Where u.ProjectId = id Select u).FirstOrDefault()

                If oDataEntity IsNot Nothing Then
                    oEntity = New ProjectVO(oDataEntity)
                End If
            End Using

            Return oEntity

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try


    End Function

    ' ''' <summary>
    ' ''' Gets the specified login.
    ' ''' </summary>
    ' ''' <param name="login">The id.</param>
    ' ''' <returns></returns>
    'Public Function [Get](login As String) As UserVO
    '    Try
    '        '' Sin permisos y sin controller. Creado para acceder al User en el startup del proyecto FastPath
    '        Dim oEntity As UserVO

    '        Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")
    '            Dim oDataEntity As Data.BaseModel.User = (From u In oDB.Users Where u.UserLogin = login Select u).FirstOrDefault()

    '            If oDataEntity IsNot Nothing Then
    '                oEntity = New UserVO(oDataEntity)
    '            End If
    '        End Using

    '        Return oEntity

    '    Catch ex As Exception
    '        MainLib.Helpers.ExceptionWrapper(ex)
    '    End Try

    'End Function


    ''' <summary>
    ''' Get List of Projects
    ''' </summary>
    ''' <param name="SolutionId">optional for filter</param>
    ''' <returns>Array of Projects</returns>
    ''' <remarks></remarks>
    Public Function List(SolutionId As Integer) As IEnumerable(Of ProjectVO)
        Try
            Me.checkAccess("LISTPROJECTS")
            Dim oResult As New Generic.List(Of Models.Solution.ProjectVO)
            Dim oDataEntity As New Generic.List(Of Data.BaseModel.Project)

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                oDataEntity = (From c In oDB.Projects Where c.SolutionId = SolutionId Select c).ToList

                If oDataEntity IsNot Nothing Then
                    For Each dbData As Data.BaseModel.Project In oDataEntity
                        oResult.Add(New ProjectVO(dbData))
                    Next
                End If

            End Using

            Return oResult

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try
    End Function

    ''' <summary>
    ''' Update a project
    ''' </summary>
    ''' <param name="project"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Update(project As ProjectVO) As Integer
        Try
            Me.checkAccess("UPDATEPROJECT")
            Dim nRes As Integer = -1

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oData As Data.BaseModel.Project = (From c In oDB.Projects Where c.ProjectId = project.projectId Select c).FirstOrDefault()

                If oData IsNot Nothing Then
                    oData.LastUpdate = Now

                    If Not String.IsNullOrEmpty(project.name) Then
                        oData.Name = project.name
                    End If
                    If Not String.IsNullOrEmpty(project.description) Then
                        oData.Description = project.description
                    End If
                    If Boolean.TryParse(project.deleted, True) Then
                        oData.Deleted = project.deleted
                    End If

                    nRes = oDB.SaveChanges()

                End If
            End Using

            Return nRes

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
            Return Nothing
        End Try
    End Function

    ''' <summary>
    ''' CAMBIADO ESTO, ES SIN GEO DATA EL CREATE.. LUEGO SE AGREGA EN SETGEODATA
    ''' Crea un proyecto, con su respectivo arreglo de GeoData.
    ''' Y cada uno de los GeoData tiene un BoobleData, que es la info asociada.
    ''' </summary>
    ''' <param name="project"></param>
    ''' <returns>The new ID  of the entity</returns>
    ''' <remarks></remarks>
    Public Function Create(project As ProjectVO) As Integer
        Try
            Me.checkAccess("CREATEPROJECT")
            Dim nRes As Integer = -1

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oProject As New Data.BaseModel.Project()
                Dim oSolution As Data.BaseModel.Solution = (From c In oDB.Solutions Where c.SolutionId = project.solutionId Select c).FirstOrDefault()
                If oProject IsNot Nothing AndAlso oSolution IsNot Nothing Then
                    oProject.LastUpdate = Now
                    oProject.SolutionId = project.solutionId

                    If Not String.IsNullOrEmpty(project.name) Then
                        oProject.Name = project.name
                    End If
                    If Not String.IsNullOrEmpty(project.description) Then
                        oProject.Description = project.description
                    End If

                    If Boolean.TryParse(project.deleted, True) Then
                        oProject.Deleted = project.deleted
                    End If

                    oSolution.Projects.Add(oProject)
                    ' Al crear un proyecto no sera guardado ningun tipo de dato georreferenciado
                    'Dim geoD As Data.BaseModel.GeoData
                    'If project.geoDatas IsNot Nothing Then
                    '    For Each geo As GeoDataVO In project.geoDatas
                    '        If Not String.IsNullOrEmpty(geo.geoElement) Then
                    '            geoD = New Data.BaseModel.GeoData
                    '            'geoD.Name = geo.name
                    '            '' Tener en cuenta si debo agregar POINT o algo similar al guardar
                    '            'node.GeoPoint = Spatial.DbGeography.PointFromText("POINT(" & geo.pointData & ")", 4326)
                    '            geoD.GeoElement = DbGeography.FromText(geo.geoElement, 4326)

                    '            '' DEBUGGING
                    '            Console.WriteLine(geoD.GeoElement.SpatialTypeName)
                    '            '' CHEQUEAR EL DEBUGGING PARA VER SI PUEDO ASINGAR EL TYPO ASI
                    '            geoD.GeoType = New Data.BaseModel.GeoType
                    '            geoD.GeoType.Code = geoD.GeoElement.SpatialTypeName

                    '            If geo.boobleData IsNot Nothing AndAlso Not String.IsNullOrEmpty(geo.boobleData.content) Then
                    '                geoD.BoobleData = New Data.BaseModel.BoobleData
                    '                geoD.BoobleData.Content = MainLib.Helpers.json_encode(geo.boobleData.content)
                    '            End If
                    '        End If
                    '    Next
                    'End If

                    'oDB.Projects.AddObject(oProject)
                End If
                If oDB.SaveChanges() > 0 Then
                    nRes = oProject.ProjectId
                End If
            End Using

            Return nRes

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
            Return Nothing
        End Try

    End Function

    ''' <summary>
    ''' Update Geodata info on fpCase
    ''' </summary>
    ''' <param name="data"></param>
    ''' <returns>MapDataVO with id's</returns>
    ''' <remarks></remarks>
    Public Function SetGeoData(data As MapDataVO) As MapDataVO

        Dim shapeDic As New Dictionary(Of Integer, Data.BaseModel.GeoData)

        Try
            Me.checkAccess("UPDATEPROJECT")

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim project As Data.BaseModel.Project = (From e In oDB.Projects Where e.ProjectId = data.projectId Select e).FirstOrDefault()
                project.LastUpdate = Now()


                Dim geoTypes As Generic.List(Of Data.BaseModel.GeoType) = oDB.GeoTypes.ToList()

                ' delete links and nodes listed for delete
                Dim shapesToDelete As Generic.List(Of Data.BaseModel.GeoData) = (From l In oDB.GeoDatas
                                                                                            Where l.ProjectId = data.projectId And
                                                                                                    data.deletedShapes.Contains(l.GeoDataId)
                                                                                            Select l).ToList()
                '' Clear (Ver si hace falta limpiar relaciones como hace en C.P)

                '' Delete Shapes
                For Each oData As Data.BaseModel.GeoData In shapesToDelete
                    oDB.DeleteObject(oData)
                Next

                'Dim geoD As Data.BaseModel.GeoData
                'If project.geoDatas IsNot Nothing Then
                '    For Each geo As GeoDataVO In project.geoDatas
                '        If Not String.IsNullOrEmpty(geo.geoElement) Then
                '            geoD = New Data.BaseModel.GeoData
                '            'geoD.Name = geo.name
                '            '' Tener en cuenta si debo agregar POINT o algo similar al guardar
                '            'node.GeoPoint = Spatial.DbGeography.PointFromText("POINT(" & geo.pointData & ")", 4326)
                '            geoD.GeoElement = DbGeography.FromText(geo.geoElement, 4326)

                '            '' DEBUGGING
                '            Console.WriteLine(geoD.GeoElement.SpatialTypeName)
                '            '' CHEQUEAR EL DEBUGGING PARA VER SI PUEDO ASINGAR EL TYPO ASI
                '            geoD.GeoType = New Data.BaseModel.GeoType
                '            geoD.GeoType.Code = geoD.GeoElement.SpatialTypeName

                '            If geo.boobleData IsNot Nothing AndAlso Not String.IsNullOrEmpty(geo.boobleData.content) Then
                '                geoD.BoobleData = New Data.BaseModel.BoobleData
                '                geoD.BoobleData.Content = MainLib.Helpers.json_encode(geo.boobleData.content)
                '            End If
                '        End If
                '    Next
                'End If

                'add/update shapes
                
                Dim shape As Data.BaseModel.GeoData

                For Each geo As MapGeometryVO In data.geometries

                    If geo.entityId > 0 Then ' exist
                        shape = (From e In oDB.GeoDatas.Include("GeoType") Where e.GeoDataId = geo.entityId Select e).FirstOrDefault()

                        If (shape IsNot Nothing AndAlso shape.GeoType.Code <> geo.dataType) Then
                            ' Aca borra las asociaciones que tenga. TO DO: ver si hace falta
                            'For nn As Integer = shape.CasesByNode.Count - 1 To 0 Step -1
                            '    oDB.DeleteObject(node.CasesByNode(nn))
                            'Next
                            'node.IdNodeType = (From t In nodeTypes Where t.Code = geo.dataType Select t.IdNodeType).FirstOrDefault()
                            'shape.GeoTypeId = (From t In geoTypes Where t.Code = geo.dataType Select t.GeoTypeId).FirstOrDefault()
                        End If

                    Else
                        shape = New Data.BaseModel.GeoData
                        shape.ProjectId = data.projectId
                        oDB.GeoDatas.AddObject(shape)
                    End If
                    shape.GeoTypeId = (From t In geoTypes Where t.Code = geo.dataType Select t.GeoTypeId).FirstOrDefault()
                    'If geo.entityId > 0 Then ' exist
                    '    link = (From e In oDB.Links.Include("LinkType") Where e.IdLink = geo.entityId Select e).FirstOrDefault()
                    'Else
                    '    link = New FastpathData.BaseModel.Link
                    '    link.IdFPCase = data.idFPCase
                    '    oDB.Links.AddObject(link)
                    'End If

                    'link.IdLinkType = (From t In linkTypes Where t.Code = geo.dataType Select t.IdLinkType).FirstOrDefault()
                    Select Case geo.geometryType
                        Case eGeometryType.Marker
                            If Not String.IsNullOrEmpty(geo.pointData) Then
                                shape.Name = geo.name
                                shape.GeoElement = Spatial.DbGeography.PointFromText("POINT(" & geo.pointData & ")", 4326)
                                If geo.attributes.Count > 0 Then
                                    shape.ExtraData = MainLib.Helpers.json_encode(geo.attributes)
                                End If
                            End If
                            shapeDic.Add(geo.geometryId, shape)

                        Case eGeometryType.Polyline
                            If Not String.IsNullOrEmpty(geo.pointData) Then
                                shape.Name = geo.name
                                shape.GeoElement = Spatial.DbGeography.LineFromText("LINESTRING(" & geo.pointData & ")", 4326)
                                If geo.attributes.Count > 0 Then
                                    shape.ExtraData = MainLib.Helpers.json_encode(geo.attributes)
                                End If
                            End If
                            shapeDic.Add(geo.geometryId, shape)

                        Case eGeometryType.Rectangle
                            If Not String.IsNullOrEmpty(geo.pointData) Then
                                shape.Name = geo.name
                                shape.GeoElement = Spatial.DbGeography.LineFromText("LINESTRING(" & geo.pointData & ")", 4326)
                                If geo.attributes.Count > 0 Then
                                    shape.ExtraData = MainLib.Helpers.json_encode(geo.attributes)
                                End If
                            End If
                            shapeDic.Add(geo.geometryId, shape)

                        Case eGeometryType.Polygon
                            If Not String.IsNullOrEmpty(geo.pointData) Then
                                shape.Name = geo.name
                                shape.GeoElement = Spatial.DbGeography.LineFromText("LINESTRING(" & geo.pointData & ")", 4326)
                                If geo.attributes.Count > 0 Then
                                    shape.ExtraData = MainLib.Helpers.json_encode(geo.attributes)
                                End If
                            End If
                            shapeDic.Add(geo.geometryId, shape)

                        Case eGeometryType.Circle
                            If Not String.IsNullOrEmpty(geo.pointData) Then
                                shape.Name = geo.name

                                '' Error al cambiar el valor, no convierte bien los decimales que trae geo.pointData
                                '' Esta no es la forma correcta de guardar un circulo en la db.
                                shape.GeoElement = Spatial.DbGeography.PointFromText("POINT(" & geo.pointData & ")", 4326)

                                'Dim point As DbGeography = DbGeography.FromText("CIRCULARSTRING(" & geo.pointData & ")", 4326)
                                
                                If geo.attributes.Count > 0 Then
                                    shape.ExtraData = MainLib.Helpers.json_encode(geo.attributes)
                                End If

                            End If
                            shapeDic.Add(geo.geometryId, shape)
                        Case Else ''default

                    End Select
                    
                Next

                oDB.SaveChanges()

                ' fill geometries id's
                For Each geo As MapGeometryVO In data.geometries
                    geo.entityId = shapeDic(geo.geometryId).GeoDataId
                Next

            End Using

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try

        Return data

    End Function


    ''' <summary>
    ''' Return geodata info from Project
    ''' </summary>
    ''' <param name="id">project ID</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetGeoData(id As Integer) As MapDataVO
        Dim res As New MapDataVO
        res.projectId = id

        Try
            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oShapes As Generic.List(Of Data.BaseModel.GeoData) = (From n In oDB.GeoDatas Where n.ProjectId = id Select n).ToList()
                Dim geometry As MapGeometryVO

                For Each oShape As Data.BaseModel.GeoData In oShapes
                    Select Case oShape.GeoType.Code
                        Case "MARKER"

                            geometry = New MapGeometryVO()
                            geometry.entityId = oShape.GeoDataId
                            geometry.geometryType = eGeometryType.Marker
                            geometry.dataType = oShape.GeoType.Code
                            geometry.name = oShape.Name
                            geometry.points.Add(New MapPoint(oShape.GeoElement.Latitude, oShape.GeoElement.Longitude))
                            If Not String.IsNullOrEmpty(oShape.ExtraData) Then
                                geometry.attributes = MainLib.Helpers.json_decode(Of Generic.List(Of MapAttribute))(oShape.ExtraData)
                            End If
                            res.geometries.Add(geometry)

                        Case "POLYGON"
                            geometry = New MapGeometryVO()
                            geometry.entityId = oShape.GeoDataId
                            geometry.geometryType = eGeometryType.Polygon
                            geometry.dataType = oShape.GeoType.Code
                            geometry.name = oShape.Name
                            For nn As Integer = 1 To oShape.GeoElement.PointCount
                                geometry.points.Add(New MapPoint(oShape.GeoElement.PointAt(nn).Latitude, oShape.GeoElement.PointAt(nn).Longitude))
                            Next
                            If Not String.IsNullOrEmpty(oShape.ExtraData) Then
                                geometry.attributes = MainLib.Helpers.json_decode(Of Generic.List(Of MapAttribute))(oShape.ExtraData)
                            End If
                            res.geometries.Add(geometry)
                        Case "RECTANGLE"
                            geometry = New MapGeometryVO()
                            geometry.entityId = oShape.GeoDataId
                            geometry.geometryType = eGeometryType.Rectangle
                            geometry.dataType = oShape.GeoType.Code
                            geometry.name = oShape.Name
                            For nn As Integer = 1 To oShape.GeoElement.PointCount
                                geometry.points.Add(New MapPoint(oShape.GeoElement.PointAt(nn).Latitude, oShape.GeoElement.PointAt(nn).Longitude))
                            Next
                            If Not String.IsNullOrEmpty(oShape.ExtraData) Then
                                geometry.attributes = MainLib.Helpers.json_decode(Of Generic.List(Of MapAttribute))(oShape.ExtraData)
                            End If
                            res.geometries.Add(geometry)
                        Case "CIRCLE"
                            geometry = New MapGeometryVO()
                            geometry.entityId = oShape.GeoDataId
                            geometry.geometryType = eGeometryType.Circle
                            geometry.dataType = oShape.GeoType.Code
                            geometry.name = oShape.Name
                            geometry.points.Add(New MapPoint(oShape.GeoElement.Latitude, oShape.GeoElement.Longitude))
                            If Not String.IsNullOrEmpty(oShape.ExtraData) Then
                                geometry.attributes = MainLib.Helpers.json_decode(Of Generic.List(Of MapAttribute))(oShape.ExtraData)
                                'geometry.attributes = MainLib.Helpers.json_decode(Of Generic.List(Of Object))(oShape.ExtraData)
                            End If
                            res.geometries.Add(geometry)
                        Case "POLYLINE"
                            geometry = New MapGeometryVO()
                            geometry.entityId = oShape.GeoDataId
                            geometry.geometryType = eGeometryType.Polyline
                            geometry.dataType = oShape.GeoType.Code
                            geometry.name = oShape.Name
                            For nn As Integer = 1 To oShape.GeoElement.PointCount
                                geometry.points.Add(New MapPoint(oShape.GeoElement.PointAt(nn).Latitude, oShape.GeoElement.PointAt(nn).Longitude))
                            Next
                            If Not String.IsNullOrEmpty(oShape.ExtraData) Then
                                geometry.attributes = MainLib.Helpers.json_decode(Of Generic.List(Of MapAttribute))(oShape.ExtraData)
                            End If
                            res.geometries.Add(geometry)

                    End Select

                Next

            End Using

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try

        Return res
    End Function

    ''' <summary>
    ''' Return geo attributes of a Project
    ''' </summary>
    ''' <param name="projectId">Project ID</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetGeoAttributes(projectId As Integer) As Dictionary(Of String, Generic.List(Of Generic.KeyValuePair(Of String, String)))
        Dim res As New Dictionary(Of String, Generic.List(Of Generic.KeyValuePair(Of String, String)))
        Dim key As String
        Try

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim shapes As Generic.List(Of Data.BaseModel.GeoData) = (From e In oDB.GeoDatas.Include("GeoType")
                                                                                            Where e.ProjectId = projectId
                                                                                            Select e).ToList()

                For Each shape As Data.BaseModel.GeoData In shapes
                    key = "shape" & shape.GeoDataId
                    fillAttributeDictionary(res, key, shape)
                Next

                'Dim linkDetails As Generic.List(Of FastpathData.BaseModel.LinkDetail) = (From e In oDB.LinkDetails.Include("LinkAttribute")
                '                                                                            Where e.Link.IdFPCase = fpCaseId And e.IdScenario = scenarioId
                '                                                                            Select e).ToList()

                'Dim nodeDetails As Generic.List(Of FastpathData.BaseModel.NodeDetail) = (From e In oDB.NodeDetails.Include("NodeAttribute")
                '                                                                            Where e.Node.IdFPCase = fpCaseId And e.IdScenario = scenarioId
                '                                                                            Select e).ToList()


                'Dim subCorridors As Generic.List(Of FastpathData.BaseModel.Subcorridor) = (From e In oDB.Subcorridors Where e.Corridor.CorridorNetwork.IdFPCase = fpCaseId Select e).ToList()
                'For Each subCorridor As FastpathData.BaseModel.Subcorridor In subCorridors

                '    For Each link As FastpathData.BaseModel.Link In subCorridor.Links
                '        key = "link" & link.IdLink
                '        fillAttributeDictionary(res, key, subCorridor, link, Nothing, linkDetails, nodeDetails)

                '        If link.NodeA IsNot Nothing Then
                '            key = "node" & link.NodeA.IdNode
                '            link.NodeA.NodeDetails.Any(Function(d) d.IdScenario = scenarioId)
                '            fillAttributeDictionary(res, key, subCorridor, Nothing, link.NodeA, linkDetails, nodeDetails)
                '        End If
                '        If link.NodeB IsNot Nothing Then
                '            key = "node" & link.NodeB.IdNode
                '            link.NodeB.NodeDetails.Any(Function(d) d.IdScenario = scenarioId)
                '            fillAttributeDictionary(res, key, subCorridor, Nothing, link.NodeB, linkDetails, nodeDetails)
                '        End If
                '    Next
                'Next
            End Using

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try

        Return res
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="dic"></param>
    ''' <param name="key"></param>
    ''' <param name="shape"></param>
    ''' <remarks></remarks>
    Private Sub fillAttributeDictionary(ByRef dic As Dictionary(Of String, Generic.List(Of Generic.KeyValuePair(Of String, String))), ByVal key As String, ByRef shape As Data.BaseModel.GeoData)


        If Not dic.ContainsKey(key) Then
            dic.Add(key, New Generic.List(Of Generic.KeyValuePair(Of String, String)))
            dic(key).Add(New Generic.KeyValuePair(Of String, String)("Project", shape.Project.Name))
            dic(key).Add(New Generic.KeyValuePair(Of String, String)("Shape", shape.Name))
            dic(key).Add(New Generic.KeyValuePair(Of String, String)("GeoType", shape.GeoType.Code))

            dic(key).Add(New Generic.KeyValuePair(Of String, String)("GeoElement" & shape.GeoDataId, shape.GeoElement.ToString))

            'dic(key).Add(New Generic.KeyValuePair(Of String, String)("FPCase", subCorridor.Corridor.CorridorNetwork.FPCase.Name))
            'dic(key).Add(New Generic.KeyValuePair(Of String, String)("SCorridor", subCorridor.Name))
            'dic(key).Add(New Generic.KeyValuePair(Of String, String)("Corridor", subCorridor.Corridor.Name))
            'If link IsNot Nothing Then
            '    dic(key).Add(New Generic.KeyValuePair(Of String, String)("ItemType", link.LinkType.Code))
            'ElseIf node IsNot Nothing Then
            '    dic(key).Add(New Generic.KeyValuePair(Of String, String)("ItemType", node.NodeType.Code))
            'End If
            'If link IsNot Nothing AndAlso linkDetails IsNot Nothing AndAlso linkDetails.Count > 0 Then
            '    Dim id As Integer = link.IdLink
            '    For Each ld As FastpathData.BaseModel.LinkDetail In (From l In linkDetails Where l.IdLink = id Select l).ToList
            '        If Not String.IsNullOrEmpty(ld.Value) Then
            '            dic(key).Add(New Generic.KeyValuePair(Of String, String)("FP" & ld.IdLinkAttribute, ld.Value))
            '        End If
            '    Next
            'End If
            'If node IsNot Nothing AndAlso nodeDetails IsNot Nothing AndAlso nodeDetails.Count > 0 Then
            '    Dim id As Integer = node.IdNode
            '    For Each nd As FastpathData.BaseModel.NodeDetail In (From n In nodeDetails Where n.IdNode = id Select n).ToList
            '        If Not String.IsNullOrEmpty(nd.Value) Then
            '            dic(key).Add(New Generic.KeyValuePair(Of String, String)("FP" & nd.IdNodeAttribute, nd.Value))
            '        End If
            '    Next
            'End If

        Else
            'Update?
            ' find next slot
            'Dim skipAdd As Boolean = False
            'For nn As Integer = 1 To 9
            '    Dim found As Boolean = False
            '    For Each pair As Generic.KeyValuePair(Of String, String) In dic(key)
            '        If pair.Key.StartsWith("SCorridor") AndAlso pair.Value = subCorridor.Name Then
            '            skipAdd = True
            '            Exit For
            '        End If

            '        If pair.Key = "Corridor" & nn.ToString Then
            '            found = True
            '            Exit For
            '        End If
            '    Next
            '    If skipAdd Then
            '        Exit For
            '    End If
            '    If Not found Then
            '        dic(key).Add(New Generic.KeyValuePair(Of String, String)("SCorridor" & nn, subCorridor.Name))
            '        dic(key).Add(New Generic.KeyValuePair(Of String, String)("Corridor" & nn, subCorridor.Corridor.Name))
            '        Exit For
            '    End If
            'Next
        End If
    End Sub

    ''' <summary>
    ''' Delete a project
    ''' </summary>
    ''' <param name="id">projectId</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Delete(id As Integer) As Integer
        Try
            Me.checkAccess("DELETEPROJECT")
            Dim nRes As Integer = -1

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oData As Data.BaseModel.Project = (From c In oDB.Projects Where c.ProjectId = id Select c).FirstOrDefault()

                If oData IsNot Nothing Then
                    oDB.DeleteObject(oData)
                    nRes = oDB.SaveChanges()
                End If

            End Using

            Return nRes

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
            Return Nothing
        End Try

    End Function

End Class